package com.masterclient.app.businessmodule.vipmodule.financial_management.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.eoner.baselib.activity.FCBaseActivity;
import com.eoner.baselib.widget.navgation.FCNavigationBar;
import com.eoner.baselibrary.utils.Utils;
import com.eoner.baselibrary.utils.ViewTransformUtil;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.system.SystemConfigStorage;
import com.eoner.managerlibrary.user.UserDataManager;
import com.eoner.middlelib.router.map.FCRouterPath;
import com.masterclient.app.R;
import com.masterclient.app.businessmodule.vipmodule.financial_management.bean.BankCardBean;
import com.masterclient.app.businessmodule.vipmodule.financial_management.bean.CashBaseInfoData;
import com.masterclient.app.businessmodule.vipmodule.financial_management.contract.CashIndexContract;
import com.masterclient.app.businessmodule.vipmodule.financial_management.contract.CashIndexPresenter;
import com.masterclient.app.modules.bridge.BridgeActivity;
import com.masterclient.app.utils.CaptchaUtil;

import java.math.BigDecimal;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = FCRouterPath.CASH_INDEX)
public class CashIndexActivity extends FCBaseActivity<CashIndexPresenter> implements CashIndexContract.View {

    @BindView(R.id.cash_protocol_text)
    TextView cashProtocolText;
    @BindView(R.id.cash_protocol_box)
    CheckBox cashProtocolBox;
    @BindView(R.id.cash_edit)
    EditText cashEdit;
    @BindView(R.id.cash_edit_hint)
    TextView cashEditHint;
    @BindView(R.id.cash_all)
    TextView cashAll;
    @BindView(R.id.cash_edit_desc)
    TextView cashEditDesc;
    @BindView(R.id.cash_code_et)
    EditText cashCodeEt;
    @BindView(R.id.cash_code_send)
    TextView cashCodeSend;
    @BindView(R.id.cash_bank_name)
    TextView cashBankName;
    @BindView(R.id.cash_bank_logo)
    ImageView cashBankLogo;
    @BindView(R.id.cash_submit)
    TextView cashSubmit;
    @BindView(R.id.tips_tv)
    TextView tipsTv;

    @Autowired(name = "source")
    String source;

    private static final int REQUEST_CODE = 3;
    private String bankcard_cert_id;
    private float moneyTotal = 0;
    private float editMoney = 0;
    private CaptchaUtil captchaUtil;
    private CountDownTimer timer;
    private String protocol_target;

    @Override
    protected int requireGetLayoutId() {
        return R.layout.activity_cash_index;
    }

    @Override
    protected void requireSetCustomNavigationBar(FCNavigationBar navigationBar) {
        navigationBar.setTitle("提现").setRightBtnText("提现记录").setRightBtnTextColor(Color.parseColor("#666666"));
    }

    @Override
    protected void requireInitUIAndData(Bundle savedInstanceState) {

        captchaUtil = new CaptchaUtil(mContext, "提现");
        captchaUtil.setCaptchaListerner(new CaptchaUtil.CaptchaListerner() {
            @Override
            public void onSuccess(String ne) {

                if (!TextUtils.isEmpty(UserDataManager.getInstance().getMobile())) {
                    mPresenter.getCaptcha(UserDataManager.getInstance().getMobile(), "withdraw", ne);
                    cashCodeSend.setClickable(false);
                }
            }

            @Override
            public void onFailed() {
                cashCodeSend.setClickable(true);
            }
        });


        cashEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if (s.toString().equals(".")){
                    cashEdit.getText().clear();
                }

                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0, s.toString().indexOf(".") + 3);
                        cashEdit.setText(s);
                        cashEdit.setSelection(s.length());
                    }
                }

                cashEditHint.setVisibility(s.length()>0?View.GONE:View.VISIBLE);

                String editStr = cashEdit.getText().toString();
                if (TextUtils.isEmpty(editStr)){
                    editMoney = 0;
                }else {
                    if (editStr.endsWith(".")){
                        editMoney = Float.parseFloat(editStr.substring(0,editStr.length()-1));
                    }else {
                        editMoney = Float.parseFloat(editStr);
                    }
                }
                if (editMoney>moneyTotal){
                    cashEditDesc.setText("金额超过可提余额");
                    cashEditDesc.setTextColor(Color.parseColor("#f1444d"));
                }else {
                    cashEditDesc.setText(new StringBuffer("可提余额:¥").append(Utils.decimalFormat(new BigDecimal(moneyTotal))));
                    cashEditDesc.setTextColor(Color.parseColor("#2995e6"));
                }

                cashSubmit.setBackgroundColor(Color.parseColor(editMoney<=moneyTotal&&editMoney>0?"#212121":"#cccccc"));
                cashSubmit.setEnabled(editMoney<=moneyTotal&&editMoney>0);

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mPresenter.getBaseInfo(source,true);
    }

    @Override
    protected void onNavigationRightClick() {
        ARouter.getInstance().build(FCRouterPath.CASH_RECORD).withString("source",source).navigation();
    }


    @OnClick({R.id.cash_protocol_link,R.id.cash_all,R.id.cash_bank_layout,R.id.cash_code_send,R.id.cash_submit})
    void onClick(View view){
        switch (view.getId()){
            case R.id.cash_protocol_link:
                startActivitryWithBundle(BridgeActivity.class, new String[][]{{"url", protocol_target}, {"title", "用户协议"}});
                break;
            case R.id.cash_all:
                if (moneyTotal>0) {
                    cashEdit.setText(String.valueOf(moneyTotal));
                    cashEdit.setSelection(String.valueOf(moneyTotal).length());
                }
                break;
            case R.id.cash_bank_layout:
                ARouter.getInstance().build(FCRouterPath.BANK_LIST).navigation(this,REQUEST_CODE);
                break;
            case R.id.cash_submit:
                if (!cashProtocolBox.isChecked()){
                    showToast("请先同意《云账户用户协议》");
                    return;
                }
                if (TextUtils.isEmpty(bankcard_cert_id)){
                    showToast("请选择银行卡");
                    return;
                }

                if (TextUtils.isEmpty(cashCodeEt.getText().toString())){
                    showToast("请输入验证码");
                    return;
                }

                mPresenter.applyCash(String.valueOf(editMoney),bankcard_cert_id,UserDataManager.getInstance().getMobile(),cashCodeEt.getText().toString(),source);
                break;
            case R.id.cash_code_send:

                if (SystemConfigStorage.getInstance().isOpenSlipPageCode()) {
                    if (CaptchaUtil.CAPTCHA_NUMBER_TIMES >= Config.CAPTCHA_MAX_TIMES) {
                        mPresenter.getCaptcha(UserDataManager.getInstance().getMobile(), "withdraw", "");
                    } else {
                        captchaUtil.start();
                    }
                } else {
                    cashCodeSend.setClickable(false);
                    mPresenter.getCaptcha(UserDataManager.getInstance().getMobile(), "withdraw", "");
                }

                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK){
            BankCardBean bankcardBean = (BankCardBean) data.getSerializableExtra("bank_card");
            ViewTransformUtil.glideImageView(getActivity(),bankcardBean.cardBg,cashBankLogo,R.drawable.flower_placeholder);
            cashBankName.setText(bankcardBean.bankShort);
            bankcard_cert_id = bankcardBean.bankcardCertId;
        }
    }

    @Override
    public void showData(CashBaseInfoData dataBean) {
        protocol_target = dataBean.getProtocol_target();
        bankcard_cert_id = dataBean.getBankcard_cert_id();
        if (!TextUtils.isEmpty(bankcard_cert_id)){
            ViewTransformUtil.glideImageView(getActivity(),dataBean.getBankcard_icon(),cashBankLogo,R.drawable.flower_placeholder);
            cashBankName.setText(dataBean.getBank_short_name());
        }
        moneyTotal = dataBean.getAvailable_balance();
        cashEditDesc.setText(new StringBuffer("可提余额:¥").append(Utils.decimalFormat(new BigDecimal(moneyTotal))));
        cashEditDesc.setTextColor(Color.parseColor("#2995e6"));
        cashSubmit.setBackgroundColor(Color.parseColor("#cccccc"));
        cashSubmit.setEnabled(false);
        String tips = dataBean.getTips();
        if(!TextUtils.isEmpty(tips)){
            tips = tips.replaceAll("#n","\n");
            tips = tips.replaceAll(" ","");
            tipsTv.setText(tips);
        }

    }

    @Override
    public void failureData() {

    }

    @Override
    public void captchaSuccess(boolean isSuccess) {

        if (isSuccess){
            timer = new CountDownTimer(60 * 1000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    cashCodeSend.setTextColor(Color.parseColor("#999FAA"));
                    String timeStr = millisUntilFinished / 1000 + "s";
                    String temp = timeStr + "后重发";

                    SpannableString spannableString = new SpannableString(temp);
                    spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#397BE6")), 0, timeStr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    cashCodeSend.setText(spannableString);
                    cashCodeSend.setBackgroundResource(0);
                }

                @Override
                public void onFinish() {
                    cashCodeSend.setClickable(true);
                    String timeStr = "重新获取";
                    cashCodeSend.setBackgroundResource(R.drawable.text_underline_397be6);

                    SpannableString spannableString = new SpannableString(timeStr);
                    spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#397BE6")), 0, timeStr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    cashCodeSend.setText(spannableString);
                }
            };
            timer.start();
        }else {
            cashCodeSend.setClickable(true);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    @Override
    public void applyResult(boolean isSuccess, String msg) {
        if (isSuccess){
            ARouter.getInstance().build(FCRouterPath.ORDER_PAY_SUCCESS).withString("msg",msg).navigation();
            //  finish();
        }else {
            showToast(msg);
        }

    }

    protected void startActivitryWithBundle(@NonNull Class clazz, String[][] val) {
        Intent intent = new Intent(this, clazz);
        Bundle bundle = new Bundle();
        if (val != null) {
            for (String[] aVal : val) {
                bundle.putString(aVal[0], aVal[1]);
            }
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }
}
